package com.goldenautumn.prefabricate.activity.home

import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.goldenautumn.prefabricate.MainActivity
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.category.CategoryLayoutAdapter
import com.goldenautumn.prefabricate.activity.mall.GoodsDetailsActivity
import com.goldenautumn.prefabricate.activity.mall.adapter.CenterLayoutManager
import com.goldenautumn.prefabricate.activity.search.SearchActivity
import com.goldenautumn.prefabricate.business.entity.GoodsInfoVO
import com.goldenautumn.prefabricate.business.entity.GoodsSkuVo
import com.goldenautumn.prefabricate.business.entity.TabInfoVo
import com.goldenautumn.prefabricate.business.mall.HomeDataUiState
import com.goldenautumn.prefabricate.business.mall.MallViewModel
import com.goldenautumn.prefabricate.business.user.LoadingUiState
import com.goldenautumn.prefabricate.databinding.FragmentHomeBinding
import com.goldenautumn.prefabricate.utils.Constants
import com.goldenautumn.prefabricate.utils.Constants.BUSINESS_PAGE_DATA
import com.gyf.immersionbar.ImmersionBar
import com.scwang.smart.refresh.layout.api.RefreshFooter
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.simple.SimpleMultiListener
import com.youth.banner.indicator.RectangleIndicator
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseFragment
import qncx.external.common.compat.isVisible
import qncx.external.common.compat.visible
import qncx.external.common.utils.intent
import qncx.external.common.widget.consecutive.ConsecutiveScrollerLayout.OnScrollChangeListener
import qncx.external.common.widget.tabLayout.ViewPager2Adapter

class HomeFragment : BaseFragment<FragmentHomeBinding>() {

    private val mMallModel by viewModels<MallViewModel>()

    private val mRecommendAdapter by lazy {
        HomeRecommendAdapter()
    }

    private val mAdapter by lazy {
        CategoryLayoutAdapter()
    }

    val menuBannerAdapter = HomeMenuBannerAdapter(arrayListOf())

    override fun getLayoutId(): Int = R.layout.fragment_home

    override suspend fun initView() {
        initImmersionBar()
        ImmersionBar.setTitleBar(this, mBinding.toolbar)

        mBinding.recommendRv.layoutManager = LinearLayoutManager(mContext,RecyclerView.HORIZONTAL,false)
        mBinding.recommendRv.adapter = mRecommendAdapter
        mBinding.goodsRv.layoutManager = GridLayoutManager(mContext,2)
        mBinding.goodsRv.adapter = mAdapter

        mBinding.searchBtn.setOnClickListener {
            startActivity(SearchActivity::class.intent)
        }

        mBinding.searchBadge.setOnClickListener {
            startActivity(SearchActivity::class.intent)
        }

        mAdapter.setOnItemClickListener{ adapter,_,position ->
            val item = adapter.getItem(position)
            startActivity(GoodsDetailsActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,item?.goods_id))
        }

        mBinding.menuBanner.setAdapter(menuBannerAdapter)
            .addBannerLifecycleObserver(this) //添加生命周期观察者
            .setIndicator(RectangleIndicator(mContext)) //设置指示器

        mRecommendAdapter.setOnItemClickListener { adapter,_,position ->
            val item = adapter.getItem(position)
            startActivity(GoodsDetailsActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,"${item?.goods_id}".toInt()))
        }

        mBinding.refresh.setOnMultiListener(object :SimpleMultiListener() {

            override fun onFooterMoving(footer: RefreshFooter?, isDragging: Boolean, percent: Float, offset: Int, footerHeight: Int, maxDragHeight: Int) {
                super.onFooterMoving(footer, isDragging, percent, offset, footerHeight, maxDragHeight)
                // 上拉加载时，保证吸顶头部不被推出屏幕。
                // 如果你本身就设置了吸顶偏移量，那么这里的offset计算你的偏移量加offset
                mBinding.scroller.stickyOffset = offset
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                super.onRefresh(refreshLayout)
                mMallModel.getHomeData()
            }

        })

        var mScrollY = 0

        mBinding.scroller.onVerticalScrollChangeListener = object :OnScrollChangeListener {

            private var lastScrollY = 0
            private var h = SizeUtils.dp2px(130f)

            override fun onScrollChange(v: View?, scrollY: Int, oldScrollY: Int, scrollState: Int) {
                if (scrollY > oldScrollY) {
                    // 向上滑动
                    LogUtils.d(">>>>>>>向上滑动${scrollY}")
                } else if (scrollY < oldScrollY) {
                    // 向下滑动
                    LogUtils.d(">>>>>>>向下滑动${scrollY}")
                }
                mBinding.imageView6.translationY = -scrollY.toFloat()
                var _scrollY = scrollY
                if (lastScrollY < h) {
                    _scrollY = h.coerceAtMost(_scrollY)
                    mScrollY = if (_scrollY > h) h else _scrollY
                    var values = 1f * mScrollY / h
                    mBinding.toolbar.isVisible(values > 0)
                    mBinding.toolbar.alpha = values
                    mBinding.searchBadge.alpha = 1 - values

                }
                lastScrollY = _scrollY

            }
        }

//        val money1 = Money("10.01")
//        val money2 = Money("20")
//
//        val sum = money1 + money2
//        val difference = money1 - money2
//        val product = money1 * money2
//        val quotient = money1 / money2
//
//        LogUtils.d("Sum: $sum")
//        LogUtils.d("Difference: $difference")
//        LogUtils.d("Product: $product")
//        LogUtils.d("Quotient: $quotient")


        mMallModel.getHomeData()
        while (isActive) {
            select {
                mMallModel.loading.onReceive {
                    when(it) {
                        is LoadingUiState.LoadingUI -> {
                            if(!it.isShow) {
                                mBinding.refresh.finishRefresh()
                                mBinding.refresh.finishLoadMore()
                            } else {}
                        }

                        else -> {}
                    }
                }
                mMallModel.homeDataReq.onReceive {
                    when(it) {
                        is HomeDataUiState.BannerData -> {

                        }
                        is HomeDataUiState.HomeMenu -> {
                            var arr = splitArr(it.menus,4)
                            menuBannerAdapter.setDatas(arr)
                            mBinding.menuBanner.setCurrentItem(1,false)
                            mBinding.menuBanner.setCurrentItem(0,false)
                        }
                        is HomeDataUiState.HomeHit -> {
                            mRecommendAdapter.submitList(it.hit)
                        }
                        is HomeDataUiState.HomeTab -> {
                            mBinding.goodsRv.visible()

                            val data = it.tab?.get(0)?.data

                            val datas = ArrayList<GoodsInfoVO>()
                            data?.forEach {
                                datas.add(
                                    GoodsInfoVO(
                                    goods_id = "${it.goods_id}".toInt(),
                                    goods_image = it.goods_image,
                                    goods_name = it.goods_name,
                                    goods_sku = GoodsSkuVo(goods_price = it.goods_price))
                                )
                            }

                            mAdapter.submitList(datas)
                        }
                        else -> {}
                    }
                }
            }
        }

    }

    private fun <T> splitArr(array: List<T>, num: Int): List<List<T>> {
        val count = if (array.size % num == 0) array.size / num else array.size / num + 1
        val arrayList: MutableList<List<T>> = ArrayList()
        for (i in 0 until count) {
            var index = i * num
            val list: MutableList<T> = ArrayList()
            var j = 0
            while (j < num && index < array.size) {
                list.add(array[index++])
                j++
            }
            arrayList.add(list)
        }
        return arrayList
    }

    override fun onResume() {
        super.onResume()
        initImmersionBar()
    }

}